package com.third.bank.util;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 随机生成不重复银行卡工具类
 */
public class RandomBankCardUtils {

    private static final Set<String> USED_BANK_CARD = new HashSet<>();

    public static synchronized String generateRandomBankCardNumber() {
        String bankCardNumber;
        do {
            bankCardNumber = generateBankCardNumber();
        } while (USED_BANK_CARD.contains(bankCardNumber));
        USED_BANK_CARD.add(bankCardNumber);
        return bankCardNumber;
    }

    private static String generateBankCardNumber() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        // 生成前缀 6 位数字
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }

        // 生成主体部分 12 位数字
        for (int i = 0; i < 12; i++) {
            sb.append(random.nextInt(10));
        }

        // 计算校验码并添加到卡号末尾(将每一位数据相加取模）
        String cardNumber = sb.toString();
        int sum = 0;
        for (int i = 0; i < cardNumber.length(); i++) {
            int digit = cardNumber.charAt(i) - '0';
            sum += digit;
        }
        int checksum = (10 - sum % 10) % 10;
        sb.append(checksum);

        return sb.toString();
    }
}

